package com.szgr.baoyin.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.szgr.baoyin.MyApplication;
import com.szgr.baoyin.R;
import com.szgr.baoyin.utils.Constant;
import com.szgr.baoyin.utils.MyTool;
import com.szgr.baoyin.utils.ToastUtils;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;

/**
 * 我要提问
 */
public class QuestionActivity extends BaseActivity {

    private String board_id;
    private EditText et_title;
    private EditText et_content;
    private String bid;
    private String tid;
    private boolean isFromDetail = false;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 32:
                    if(!isFromDetail) {
                        ToastUtils.showToast("发表成功");
                    }else{
                        ToastUtils.showToast("回复成功");
                    }
                    setResult(98,new Intent());
                    finish();
                    break;
                case 33:
                    if(!isFromDetail) {
                        ToastUtils.showToast((String) msg.obj);
                    }else{
                        ToastUtils.showToast((String) msg.obj);
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_question);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initActionBar() {

    }

    @Override
    public void initView() {
        Intent intent = getIntent();
        if (intent.hasExtra("board_id")) {
            board_id = intent.getStringExtra("board_id");
        }

        if(intent.hasExtra("bid")){
            bid = intent.getStringExtra("bid");
            tid = intent.getStringExtra("tid");
            isFromDetail = true;
        }

        et_title = (EditText) findViewById(R.id.question_title);
        et_content = (EditText) findViewById(R.id.question_content);
        Button btn_sub = (Button) findViewById(R.id.question_submit);
        btn_sub.setOnClickListener(this);

        if(!isFromDetail) {
            actionBarTitle.setText("我要发帖");
            btn_sub.setText("发表帖子");
        }else{
            actionBarTitle.setText("我要回复");
            btn_sub.setText("回复帖子");
            et_title.setVisibility(View.GONE);
            findViewById(R.id.question_line).setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.action_bar_left:
                finish();
                break;
            case R.id.question_submit:

                JSONArray content = new JSONArray();
                try {
                    JSONObject con = new JSONObject();
                    con.put("type", "0");
                    con.put("infor", MyTool.getText(et_content));

                    content.put(con);

                    JSONObject body = new JSONObject();
                    if(isFromDetail) {
                        body.put("tid", tid);
                        body.put("fid", bid);
                    }else{
                        body.put("fid", board_id);
                        body.put("tid", "");
                    }
                    body.put("typeOption", new JSONObject());
                    body.put("isAnonymous", 0);
                    body.put("isOnlyAuthor", 0);
                    body.put("typeId", 0);
                    body.put("sortId", 0);
                    body.put("isQuote", 0);
                    body.put("replyId", "");
                    body.put("isShowPostion", 0);
                    body.put("longitude", "");
                    body.put("latitude", "");
                    body.put("location", "");
                    body.put("title", MyTool.getText(et_title));
                    body.put("aid", "");
                    body.put("content", content);

                    JSONObject result = new JSONObject();

                    result.put("json", body);

                    JSONObject res = new JSONObject();
                    res.put("body",result);

                    if(isFromDetail) {
                        submitQuestion("reply", res.toString());
                    }else{
                        submitQuestion("new", res.toString());
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }


                break;
        }
    }

    private void submitQuestion(final String act, final String jsonObject) {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_SEND_REPLY,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        System.out.println("-------->" + s);
                        try {
                            JSONObject json = new JSONObject(s);
                            JSONObject head = json.getJSONObject("head");
                            String errCode = head.getString("errCode");
                            if("00000000".equals(errCode)){
                                mHandler.obtainMessage(32).sendToTarget();
                            }else{
                                String errInfo = head.getString("errInfo");
                                mHandler.obtainMessage(33,errInfo).sendToTarget();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put("accessToken", MyApplication.getmInstance().getToken());
                map.put("accessSecret", MyApplication.getmInstance().getSecret());
                map.put("act", act);
                map.put("json", jsonObject);
                System.out.println("-----params---->" + map.toString());
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    private void subQuestion(final String act,final JSONObject jsonObject){
        AsyncHttpClient client = new AsyncHttpClient();
        client.setTimeout(60 * 1000);
        RequestParams params = new RequestParams();
        params.put("accessToken", MyApplication.getmInstance().getToken());
        params.put("accessSecret", MyApplication.getmInstance().getSecret());
        params.put("act", act);
        params.put("json", jsonObject);
        System.out.println("-----params---->" + jsonObject.toString());

        client.post(Constant.URL_SEND_REPLY,params,new JsonHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                if(response != null){
                    System.out.println("---result1--->" + response.toString());
                }
            }

            @Override
            public void onFailure(int statusCode, Throwable e, JSONObject errorResponse) {
                System.out.println("---result2--->" + errorResponse.toString());
            }
        });
    }
}
